import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueSetupExtend from "vite-plugin-vue-setup-extend";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import { resolve } from "path";
import UnoCSS from "unocss/vite";

// https://vitejs.dev/config/
// const pathSrc = path.resolve(__dirname, "src");
const pathSrc = fileURLToPath(new URL("./src", import.meta.url));

export default ({ mode }) => {
  const { VITE_PORT, VITE_BASE_URL } = loadEnv(mode, process.cwd());

  return defineConfig({
    base: VITE_BASE_URL,
    plugins: [
      vue(),
      UnoCSS({
        hmrTopLevelAwait: false,
      }),
      vueSetupExtend(),
      AutoImport({
        // 自动导入 Vue 相关函数，如：ref, reactive, toRef 等
        imports: ["vue", "vue-router", "@vueuse/core"],
        resolvers: [
          // 自动导入 Element Plus 相关函数
          ElementPlusResolver(),
          // 自动导入图标组件
          IconsResolver({ prefix: "Icon" }),
        ],
        eslintrc: {
          enabled: true, // 解决 Eslint 提示 no-undef 错误
        },
        dts: resolve(__dirname, "src/types/auto-imports.d.ts"),
      }),
      Components({
        resolvers: [
          // 自动导入 Element Plus 组件
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({ enabledCollections: ["ep"] }),
        ],
        // 指定自定义组件位置(默认:src/components)
        dirs: ["src/**/components"],
        // 配置文件位置 (false:关闭自动生成)
        dts: resolve(__dirname, "src/types/components.d.ts"),
      }),
      Icons({
        autoInstall: true,
      }),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [resolve(pathSrc, "assets/icons")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
    ],
    resolve: {
      extensions: [".js", ".vue", ".json", "es"],
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },
    css: {
      preprocessorOptions: {
        // 定义全局 SCSS 变量
        scss: {
          javascriptEnabled: true,
          additionalData: "@import '@/styles/variables.scss';",
        },
      },
    },
    preview: {
      port: 8081,
      open: true,
    },
    server: {
      https: false, // 是否开启 https
      port: VITE_PORT, // 端口号
      host: "0.0.0.0", // 监听所有地址
      open: true, // 服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      proxy: {
        // 自定义代理规则
      },
    },
    esbuild: {
      pure: ["console.log"], // 打包时移除 console.log
      drop: ["debugger"], // 打包时移除 debugger
      legalComments: "none", // 打包时移除所有注释
    },
  });
};
